package cn.client.ui.view.main.mindfulness

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.SoftwareKeyboardController
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.PopupProperties
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.DateUtils
import cn.client.data.remoteData.bean.EvaluateItem
import cn.client.data.remoteData.bean.MindfulnessRequestWithUid
import cn.client.data.remoteData.bean.PageSelectByMid
import cn.client.data.remoteData.bean.SelectUidAndMid
import cn.client.data.userStateManager
import cn.client.navigation.destinations.MindfulnessClockInPage
import cn.client.navigation.destinations.MindfulnessScorePage
import cn.client.ui.components.PlayerScreen
import cn.client.ui.view.main.chat.unread
import coil.compose.AsyncImage
import kotlinx.coroutines.launch

// 正念练习页面
@Composable
fun MindfulnessExerciseScreen(
    mid: Int,
    navController: NavController,
    viewModel: MindfulnessViewModel = hiltViewModel()
) {

    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value

    val mediaInfoState = viewModel.mindfulnessInfo.collectAsState(initial = null)
    val mediaInfo = mediaInfoState.value

    val isCollectState = viewModel.isCollect.collectAsState(initial = false)
    val isCollect = isCollectState.value

    val evaluateListState = viewModel.evaluateList.collectAsState(initial = emptyList())
    val evaluateList = evaluateListState.value

    val focusRequester = remember { FocusRequester() }
    //用于操作键盘的对象
    val keyboard = LocalSoftwareKeyboardController.current
    val coroutineScope = rememberCoroutineScope()
    val select = SelectUidAndMid(mid = mid, uid = userId)
    val pageSelect = PageSelectByMid(mid = mid, pageNo = 1, pageSize = 10)

    coroutineScope.launch {
        viewModel.dispatch(MindfulnessViewModel.PageIntent.GetMindfulnessInfo(select))
        viewModel.dispatch(MindfulnessViewModel.PageIntent.GetEvaluate(pageSelect))
    }


    Scaffold(
        topBar = {
            if (mediaInfo != null) {
                MindfulnessMediaTopBar(
                    title = mediaInfo.mediaName,
                    onClickMindfulnessMediaTopBar = {
                        coroutineScope.launch {
                            // 返回上一级
                            navController.navigateUp()
                        }
                    },
                    onClickClockIn = {
                        /* 跳转打卡页面 */
                        navController.navigate(MindfulnessClockInPage.route + "/${mediaInfo.id}")

                    },
                    onClickScore = {
                        /* 跳转新增评分页面 */
                        navController.navigate(MindfulnessScorePage.route + "/${mediaInfo.id}")
                    }
                )
            }
        },
        bottomBar = {
            MindfulnessMediaCommentField(
                focusRequester = focusRequester,
                keyboard = keyboard
            )
        }
    ) {
        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxSize()
                .background(Color.White),
        ) {
            if (mediaInfo != null) {
                // 正念媒体URL
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(260.dp)
                        .background(Color.Gray)
                ) {
                    PlayerScreen(url = mediaInfo.mediaUrl)
                }
                // 正念信息
                MindfulnessMediaInfo(
                    title = mediaInfo.mediaName,
                    pageView = mediaInfo.pageViews,
                    content = mediaInfo.mediaInfo,
                    dateTime = mediaInfo.gmtCreate
                )

                // 行为
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,//设置水平居右对齐
                ) {
                    ActionForMindfulnessMedia(
                        isCollect = isCollect,
                        collectedNum = mediaInfo.collect,
                        onClickCollect = {
                            val collect =
                                MindfulnessRequestWithUid(mid = mediaInfo.id, uid = userId)
                            if (isCollect) {
                                // 发送取消收藏意图
                                viewModel.dispatch(
                                    MindfulnessViewModel.PageIntent.UnCollectMindfulness(
                                        collect
                                    )
                                )
                            } else {
                                // 发送收藏意图
                                viewModel.dispatch(
                                    MindfulnessViewModel.PageIntent.CollectMindfulness(
                                        collect
                                    )
                                )
                            }

                        }
                    )
                }
                // 评分列表
                EvaluateForMindfulnessMedia(
                    evaluateList = evaluateList
                )
            }
        }
    }
}


@Composable
fun EvaluateForMindfulnessMedia(
    evaluateList: List<EvaluateItem>
) {
    LazyColumn(
        modifier = Modifier.fillMaxWidth()
    ) {
        items(evaluateList){
            EvaluateInfoItem(it)
        }
    }
}

@Composable
fun EvaluateInfoItem(
    evaluateItem: EvaluateItem
) {
    var isExpanded by remember { mutableStateOf(false) }
    val evaluateColor by animateColorAsState( if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface, label = "")

    Row(
        horizontalArrangement = Arrangement.Start,
        modifier = Modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier
                .width(80.dp)
                .padding(5.dp)
        ) {
            // 头像
            AsyncImage(
                model = evaluateItem.avatar,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(50.dp)
                    .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape)
                    .clip(CircleShape)
            )
            // 用户名
            Text(
                text = evaluateItem.userName,
                fontSize = 12.sp,
                color = Color.Gray,
                modifier = Modifier.padding(2.dp),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        Column(
            modifier = Modifier.fillMaxWidth()
        ) {
            Row {
                // 评分
                RatingBar(
                    currentRating = evaluateItem.score,
                    onRatingChanged = {},
                    starsColor = Color.Blue
                )
            }
            Surface(
                shape = MaterialTheme.shapes.medium,
                shadowElevation = 1.dp,
                color = evaluateColor,
                modifier = Modifier.clickable { isExpanded = !isExpanded }
            ) {
                Text(
                    text = "评分信息：${evaluateItem.info}", fontSize = 12.sp,
                    modifier = Modifier.padding(5.dp),
                    maxLines = if (isExpanded) Int.MAX_VALUE else 2,
                    style = MaterialTheme.typography.bodyMedium
                )
            }

        }
    }
}

// 行为
@Composable
fun ActionForMindfulnessMedia(
    onClickCollect: () -> Unit,
    collectedNum: Int?,
    isCollect: Boolean
) {
    Row(
        horizontalArrangement = Arrangement.Center,//设置水平居中对齐
        verticalAlignment = Alignment.CenterVertically//设置垂直居中对齐
    ) {
        /* 收藏量 */
        Text(
            text = "收藏 $collectedNum",
            color = MaterialTheme.colorScheme.secondary,
            style = MaterialTheme.typography.titleSmall
        )
        Spacer(
            modifier = Modifier
                .width(5.dp)
                .wrapContentHeight()
        )
        IconButton(onClick = {
            onClickCollect()
        }) {
            Image(
                painter = if (isCollect) painterResource(R.drawable.ic_star_yellow) else painterResource(
                    R.drawable.ic_star
                ),
                contentDescription = null
            )
        }
        Spacer(
            modifier = Modifier
                .width(5.dp)
                .wrapContentHeight()
        )
    }
}

// 正念信息
@Composable
fun MindfulnessMediaInfo(
    title: String,
    pageView: Int?,
    content: String,
    dateTime: Long
) {

    val coroutineScope = rememberCoroutineScope()
    var createDate: String = ""

    coroutineScope.launch {
        createDate = dateTime.let { it1 -> DateUtils.dateToStr(it1) }.toString()
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(5.dp)
    ) {
        Text(text = title, fontSize = 20.sp)

        /* 浏览量*/
//        Text(
//            text = "浏览 $pageView",
//            color = MaterialTheme.colorScheme.secondary,
//            style = MaterialTheme.typography.titleSmall, fontSize = 12.sp
//        )
        Spacer(
            modifier = Modifier
                .width(5.dp)
                .wrapContentHeight()
        )

        Text(text = content, fontSize = 15.sp)

        Spacer(
            modifier = Modifier
                .height(10.dp)
                .fillMaxWidth()
        )
//        Row(
//            modifier = Modifier.fillMaxWidth(),
//            horizontalArrangement = Arrangement.Center,//设置水平居中对齐
//        ) {
//            Text(text = "———— 更新于：$createDate ————", fontSize = 12.sp, color = Color.Gray)
//        }

    }
}

// 顶部栏
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MindfulnessMediaTopBar(
    onClickClockIn: () -> Unit,
    onClickScore: () -> Unit,
    title: String,
    onClickMindfulnessMediaTopBar: () -> Unit
) {
    var expanded by remember { mutableStateOf(false) }

    data class DropdownItem(val title: String, val id: Int)

    val dropdownList = listOf(
        DropdownItem("打卡", 1),
        DropdownItem("评分", 2)
    )

    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary
        ),
        title = { Text(title) },
        /* 左边按钮 */
        navigationIcon = {
            IconButton(onClick = {
                onClickMindfulnessMediaTopBar()
            }) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, null)
            }
        },
        /* 右边按钮（可以是多个） */
        actions = {
            IconButton(onClick = {
                expanded = !expanded
            }
            ) {
                Icon(Icons.Filled.MoreVert, null)
                /* 下拉框 */
                DropdownMenu(
                    expanded = expanded,
                    onDismissRequest = { expanded = !expanded }, // 当下拉菜单展开/关闭时更新状态
                    modifier = Modifier.wrapContentSize(),
                    properties = PopupProperties(
                        focusable = true,
                        dismissOnBackPress = false,
                        dismissOnClickOutside = true
                    )
                ) {
                    dropdownList.forEach { dropItem ->
                        DropdownMenuItem(
                            { Text(text = dropItem.title) },
                            onClick = {
                                expanded = false
                                when (dropItem.id) {
                                    1 -> {
                                        /* 打卡意图 */
                                        onClickClockIn()
                                    }

                                    2 -> { /* 评分意图 */
                                        onClickScore()
                                    }

                                    else -> {
                                        Unit
                                    }
                                }

                            }
                        )
                    }
                }

            }
        })
}


// 评论输入框
@Composable
fun MindfulnessMediaCommentField(
    keyboard: SoftwareKeyboardController?,
    focusRequester: FocusRequester
) {
    // 输入框
    var text by remember { mutableStateOf("") }
    //用于请求焦点的对象
    val focusManager = LocalFocusManager.current

    // 根据是否聚焦调整输入框的某些属性，例如高度
    val inputModifier = Modifier
        .fillMaxWidth()
        .padding(8.dp)
        .background(colorResource(id = R.color.white), shape = RoundedCornerShape(2.dp))
        .height(60.dp)

    Row(
        modifier = inputModifier,
        verticalAlignment = Alignment.CenterVertically,
    ) {
        BasicTextField(
            value = text,
            onValueChange = { text = it },
            modifier = Modifier
                .background(Color.LightGray, CircleShape)
                .weight(1f)
                .padding(start = 5.dp)
                .focusRequester(focusRequester)
                .fillMaxWidth(), // 确保输入框占据 Row 的剩余空间
            textStyle = TextStyle(
                color = colorResource(id = R.color.DarkGray01),
                fontSize = 16.sp,
            ),
            decorationBox = { innerTextField ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(horizontal = 2.dp)
//                        .focusRequester(focusRequester)
                ) {
                    /* 占位符 */
                    IconButton(
                        onClick = { },
                    ) {
                        Icon(
                            painterResource(id = R.drawable.ic_close_one),
                            null, tint = Color.LightGray
                        )
                    }
                    Box(
                        modifier = Modifier.weight(1f),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        innerTextField()
                    }
                    IconButton(
                        onClick = {
                            text = ""
                            // 清除焦点
                            focusManager.clearFocus()
                            /* TODO: 处理发送消息的回调 */
                        }
                    ) { Icon(imageVector = Icons.Default.Send, contentDescription = null) }
                }
            },
            keyboardActions = KeyboardActions(onSearch = {
            }),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done)
        )
    }
}